package com.ruoyi.web.controller.shopping;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.shopping.domain.MallClassify;
import com.ruoyi.shopping.domain.MallProduct;
import com.ruoyi.shopping.service.IMallClassifyService;
import com.ruoyi.shopping.service.IMallProductService;
import lombok.Data;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.shopping.domain.MallCoupons;
import com.ruoyi.shopping.service.IMallCouponsService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.swing.text.StyledEditorKit;

/**
 * 优惠券Controller
 *
 * @author ruoyi
 * @date 2022-06-09
 */
@RestController
@RequestMapping("/shopping/mallCoupons")
public class MallCouponsController extends BaseController
{
    @Autowired
    private IMallCouponsService mallCouponsService;
    @Autowired
    private IMallClassifyService mallClassifyService;
    @Autowired
    private IMallProductService productService;



    /**
     * 查询优惠券列表
     */
    @GetMapping("/getCanGiftCoupons")
    public TableDataInfo getCanGiftCoupons( MallCoupons mallCoupons)
    {
        startPage();
//        MallCoupons mallCoupons = new MallCoupons();
        List<MallCoupons> list = mallCouponsService.giveOutCoupons(mallCoupons);
        List<MallCoupons> res = new ArrayList<>();
        for (int i = 0; i < list.size() ; i++) {
            MallCoupons coupons = list.get(i);
            res.add(coupons);
        }
        return getDataTable(list);
    }


    /**
     * 优惠券查看列表
     */

    @GetMapping("/getMallCoupons")
    public AjaxResult getMallCoupons(Long id)
    {
        //分类是品类的时候查询分类信息
        MallCoupons mallCoupons = mallCouponsService.selectMallCouponsById(id);

//        mallCoupons.getParams().put("receiveStartTime",DateUtils.dateTimeYMDHSM(mallCoupons.getReceiveStartTime()));
//        mallCoupons.getParams().put("receiveEndTime",DateUtils.dateTimeYMDHSM(mallCoupons.getReceiveEndTime()));
         if(DicConstants.COUPON_TYPE_Classify.getCode().equals(mallCoupons.getCouponType())){
        String[] ids = mallCoupons.getPrimaryKey().split(",");
        List<MallClassify> getClassifyList = mallClassifyService.selectMallClassifyByIds(ids);
        List<String> couponsNames = getClassifyList.stream().map(MallClassify::getClassifyName).collect(Collectors.toList());
        StringBuilder builder = new StringBuilder();
            couponsNames.forEach(e->{
            builder.append(e).append(",");
        });
        mallCoupons.setSystematicName(builder.toString());
        }else
        //分类是商品的时候查询商品信息
        if(DicConstants.COUPON_TYPE_Product.getCode().equals(mallCoupons.getCouponType())){
            String[] ids = mallCoupons.getPrimaryKey().split(",");
            List<MallProduct> getProductList = productService.selectMallClassifyByIds(ids);
            List<String> couponsNames = getProductList.stream().map(MallProduct::getProductName).collect(Collectors.toList());
            StringBuilder builder = new StringBuilder();
            couponsNames.forEach(e->{
                builder.append(e).append(",");
        });
            mallCoupons.setSystematicName(builder.toString());
    }
        return AjaxResult.success(mallCoupons);
    }



    /**
     * 查询优惠券列表
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallCoupons:list')")
    @GetMapping("/list")
    public TableDataInfo list(MallCoupons mallCoupons)
    {
        startPage();
        List<MallCoupons> list = mallCouponsService.selectMallCouponsList(mallCoupons);
        return getDataTable(list);
    }

    /**
     * 导出优惠券列表
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallCoupons:export')")
    @Log(title = "优惠券", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MallCoupons mallCoupons)
    {
        List<MallCoupons> list = mallCouponsService.selectMallCouponsList(mallCoupons);
        ExcelUtil<MallCoupons> util = new ExcelUtil<MallCoupons>(MallCoupons.class);
        return util.exportExcel(list, "优惠券数据");
    }

    /**
     * 获取优惠券详细信息
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallCoupons:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(mallCouponsService.selectMallCouponsById(id));
    }

    /**
     * 新增优惠券
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallCoupons:add')")
    @Log(title = "优惠券", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MallCoupons mallCoupons)
    {

//        String receiveStartTime=(String)mallCoupons.getParams().get("receiveStartTime");
//        mallCoupons.setReceiveStartTime(DateUtils.parseDate(receiveStartTime));
//        String receiveEndTime=(String)mallCoupons.getParams().get("receiveEndTime");
//        mallCoupons.setReceiveEndTime(DateUtils.parseDate(receiveEndTime));


        if (mallCoupons.getReceiveStartTime() == null ||mallCoupons.getReceiveEndTime()==null){
            return AjaxResult.error("请选择可领取开始时间");
        }
        //是否固定有效期为否的时候校验可使用时间范围开始时间不能为空
        if (DicConstants.SYS_N.getCode().equals(mallCoupons.getFixedTimeState())){
            if (mallCoupons.getUseStartTime()==null ||mallCoupons.getUseEndTime()==null){
                return AjaxResult.error("请选择可使用时间");
            }
        }
        mallCoupons.setLastTotal(mallCoupons.getTotal());
        if(DicConstants.SYS_N.getCode().equals(mallCoupons.getLimitedState())){
            mallCoupons.setLastTotal(1L);
        }
        return toAjax(mallCouponsService.insertMallCoupons(mallCoupons));
    }

    /**
     * 修改优惠券
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallCoupons:edit')")
    @Log(title = "优惠券", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MallCoupons mallCoupons)
    {
        mallCoupons.setUpdateType(DicConstants.BUSINESS_Manager.getCode());
        return toAjax(mallCouponsService.updateMallCoupons(mallCoupons));
    }

    /**
     * 删除优惠券
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallCoupons:remove')")
    @Log(title = "优惠券", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mallCouponsService.logicDeleteMallCoupons(ids,DicConstants.BUSINESS_Manager.getCode(),SecurityUtils.getUserId()));
    }
}
